<?php
/**
 * ini file reader
 */
class IniReader {
    private $iniFile = '';
    private $conf = [];

    public function __construct($iniFile) {
        $this->iniFile = $iniFile;

        $this->parse();
    }

    private function parse() {
        if(false === ($fp = fopen($this->iniFile, 'r'))) {
            throw new \Exception('The ini file open failed');
        }

        $section = '';
        $key = '';
        $value = '';
        while( false !== ($line = fgets($fp, 4096)) ) {
            $line = trim($line);
            if('' === $line || ';' === $line[0]) {
                continue;
            }

            // section
            if('[' === $line[0]) {
                $section = substr($line, 1, strrpos($line, ']') - 1);

                $this->conf[$section] = [];

                continue;
            }

            // key = value
            $key = trim( substr($line, 0, strpos($line, '=')) );
            $value = trim( substr($line, strpos($line, '=') + 1) );

            $this->conf[$section][$key] = $value;
        }

        fclose($fp);
    }

    public function get($section, $key) {
        if( !isset($this->conf[$section]) ) {
            return null;
        }

        $section = $this->conf[$section];
        if( !isset($section[$key]) ) {
            return null;
        }

        return $section[$key];
    }
}
